﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using MultiThumbnail.Converters;

namespace MultiThumbnail
{
    class ThumbnailFactory
    {
        private readonly List<ThumbConverter> _converters = new List<ThumbConverter>(); 

        private static readonly ThumbnailFactory _instance = new ThumbnailFactory();

        private ThumbnailFactory(){}

        public static ThumbConverter FindConverterFor(string extension)
        {
            if (extension == null) throw new ArgumentNullException("extension");
            extension = extension.ToUpper(CultureInfo.InvariantCulture);
            var types = typeof (ThumbConverter).Assembly.GetTypes().Where(t => t.BaseType == typeof (ThumbConverter));
            return (from type in types 
                    where type.GetCustomAttributes(typeof (ExtensionAttribute), true).OfType<ExtensionAttribute>().Any(extAttr => extAttr.HasExtension(extension)) 
                    select _instance.GetConverter(type)).FirstOrDefault();
        }

        private ThumbConverter GetConverter(Type type)
        {
            foreach (var thumbConverter in _converters.Where(thumbConverter => thumbConverter.GetType() == type))
            {
                return thumbConverter;
            }
            var converter = (ThumbConverter)Activator.CreateInstance(type);
            _converters.Add(converter);
            return converter;
        }
    }
}
